package ac.il.technion.cs236369.hw5.core.servlets.orders;

import java.sql.Date;
import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;

import ac.il.technion.cs236369.hw5.core.entities.Order;
import ac.il.technion.cs236369.hw5.core.entities.Project;
import ac.il.technion.cs236369.hw5.core.entities.User;

public enum OrderParameters {

	ORDER_ID( "orderId") {
		public void saveParameters( Order order, HttpServletRequest request, EntityManager manager) {
			order.setId( Integer.valueOf( request.getParameter( toString( ))));
		}
	},
	ORDER_DATE( "date") {
		public void saveParameters( Order order, HttpServletRequest request, EntityManager manager) {
				order.setOrderDate(Date.valueOf( request.getParameter( toString( ))));
		}
	},
	ORDER_USER( "user") {
		public void saveParameters( Order order, HttpServletRequest request, EntityManager manager) {
			String param = request.getParameter( "user");
			if ( param == null) {
				return;
			}
			User user = manager.find( User.class, param);
			if ( user == null) {
				return;
			}
			order.setUser(user);
		}
	},
	ORDER_PROJECT_NAME( "projectName") {
		public void saveParameters( Order order, HttpServletRequest request, EntityManager manager) {
			String projectName = request.getParameter( toString( ));
			Query query = manager.createQuery( "SELECT p FROM Project p WHERE p.name = :name");
			Project project = (Project)query.setParameter( "name", projectName).getSingleResult( );
			order.setProject( project);
		}
	},
	ORDER_PROJECT_ID( "projectId") {
		public void saveParameters( Order order, HttpServletRequest request, EntityManager manager) {
			String projectId = request.getParameter( toString( ));
			Project project = manager.find( Project.class, projectId);
			order.setProject( project);
		}
	},
	UNDEFINED( "undefined") {
		public void saveParameters( Order order, HttpServletRequest request, EntityManager manager) {
			return;
		}
	};
	
	private String name;
	
	private static Map<String, OrderParameters> map = new HashMap<String, OrderParameters>( );
	
	static {
		for ( OrderParameters $ : OrderParameters.values( )) {
			map.put($.name, $);
		}
	}
	
	private OrderParameters( String name) {
		this.name = name;
	}
	
	@Override
	public String toString( ) {
		return name;
	}
	
	public OrderParameters fromString( String name) {
		OrderParameters $ = map.get(name);
		if (null == $) {
			$ = UNDEFINED;
		}
		return $;
	}
	
	abstract public void saveParameters( Order order, HttpServletRequest request, EntityManager manager);
}
